package mil.af.amc.adpetracker.web.actions.Model;

import mil.af.amc.adpetracker.exceptions.FileException;
import mil.af.amc.adpetracker.exceptions.ModelNotFoundException;
import mil.af.amc.adpetracker.model.Model;
import mil.af.amc.adpetracker.service.ManufacturerService;
import mil.af.amc.adpetracker.service.ModelService;
import mil.af.amc.adpetracker.web.actions.AbstractDispatchAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class ModelDispatchAction extends AbstractDispatchAction {

    Log log = LogFactory.getLog(ModelDispatchAction.class);

    private ManufacturerService manufacturerService;

    public void setManufacturerService(ManufacturerService manufacturerService) {
        this.manufacturerService = manufacturerService;
    }

    private ModelService modelService;

    public void setModelService(ModelService modelService) {
        this.modelService = modelService;
    }

    public ActionForward viewIndex(ActionMapping actionMapping,
                                   ActionForm actionForm,
                                   HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse) {

        return actionMapping.findForward("viewModelIndex");

    }

    public ActionForward viewAddModel(ActionMapping actionMapping,
                                      ActionForm actionForm,
                                      HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse) {

        return actionMapping.findForward("viewAddModel");
    }

    public ActionForward addModel(ActionMapping actionMapping,
                                  ActionForm actionForm,
                                  HttpServletRequest httpServletRequest,
                                  HttpServletResponse httpServletResponse) {

        DynaActionForm form = (DynaActionForm) actionForm;
        ActionMessages errors = form.validate(actionMapping, httpServletRequest);
        if (!errors.isEmpty()) {
            saveErrors(httpServletRequest, errors);
            actionMapping.findForward("viewAddModel");
        }

        try {
            modelService.createModel(form.getMap());
        } catch (FileException e) {
            FormFile file = (FormFile) form.get("image");
            log.debug("File Access Error", e);
            ActionMessage actionMessage = new ActionMessage("error.badimagefile", file.getFileName());
            saveError(httpServletRequest, actionMessage);
        }

        return actionMapping.findForward("viewModelIndex");
    }

    public ActionForward viewEditModel(ActionMapping actionMapping,
                                       ActionForm actionForm,
                                       HttpServletRequest httpServletRequest,
                                       HttpServletResponse httpServletResponse) {

        int id = Integer.parseInt(httpServletRequest.getParameter("modelId"));
        DynaActionForm form = (DynaActionForm) actionForm;
        Model model = modelService.getById(id);
        form.set("modelId", model.getId());
        form.set("modelName", model.getName());
        form.set("manufacturerId", model.getManufacturer().getId());
        form.set("processorSpeed", model.getProcessorSpeed());
        //form.set("image", model.getImage());

        return actionMapping.findForward("viewEditModel");

    }

    public ActionForward editModel(ActionMapping actionMapping,
                                   ActionForm actionForm,
                                   HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse) {

        DynaActionForm form = (DynaActionForm) actionForm;
        ActionMessages errors = form.validate(actionMapping, httpServletRequest);
        if (!errors.isEmpty()) {
            saveErrors(httpServletRequest, errors);
            actionMapping.findForward("viewEditModel");
        }

        try {
            modelService.editModel(form.getMap());
        } catch (FileException e) {
            log.debug("File Access Error", e);
            ActionMessage actionMessage = new ActionMessage("error.badimagefile");
            saveError(httpServletRequest, actionMessage);
        } catch (ModelNotFoundException e) {
            log.debug("File Access Error", e);
            ActionMessage actionMessage = new ActionMessage("error.badimagefile");
            saveError(httpServletRequest, actionMessage);
        }

        return actionMapping.findForward("viewAccountProfile");

    }

    public ActionForward viewImage(ActionMapping actionMapping,
                                   ActionForm actionForm,
                                   HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse) {

        int id = Integer.parseInt(httpServletRequest.getParameter("modelId"));
        Model model = modelService.getById(id);

        //Blob image = model.getImage();
        byte[] image = model.getImage();

        try {
            httpServletResponse.setContentType("image/jpeg");
            //httpServletResponse.setContentLength(image.length);
            httpServletResponse.setHeader("Content-Disposition", "inline; filename=model.jpg");

            OutputStream out = httpServletResponse.getOutputStream();
            //byte[] imageOutput = image.getBytes(1, (int) image.length());
            out.write(image);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();

        }

        return null;
    }

    /**
     * Returns a list of models by manufacturer, meant to be called via AJAX
     *
     * @param actionMapping
     * @param actionForm
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
//    public ActionForward getModelsByManufacturer(ActionMapping actionMapping,
//                                                 ActionForm actionForm,
//                                                 HttpServletRequest httpServletRequest,
//                                                 HttpServletResponse httpServletResponse) {
//
//        int manufacturerId = Integer.parseInt(httpServletRequest.getParameter("manufacturerId"));
//        Manufacturer manu = manufacturerService.getById(manufacturerId);
//
//        List<Model> modelList = modelService.getByManufacturer(manu);
//        try {
//            PrintWriter out = httpServletResponse.getWriter();
//            for (Model model : modelList) {
//                StringBuilder sb = new StringBuilder();
//                sb.append("<option value=\"");
//                sb.append(model.getId());
//                sb.append("\">");
//                sb.append(model.getName());
//                sb.append("</option>");
//                out.println(sb.toString());
//            }
//            out.flush();
//            out.close();
//        } catch (IOException e) {
//            log.debug(e);
//        }
//
//        return null;
//    }


}
